package com.itlong.cloud.sdk.service.impl;

import com.itlong.cloud.POJO.DTO.sdk.SDKAuthUserGetPageDTO;
import com.itlong.cloud.POJO.DTO.sdk.SDKRoomInfoSaveDTO;
import com.itlong.cloud.POJO.DTO.sdk.SDKSaveAppUserDTO;
import com.itlong.cloud.POJO.PO.*;
import com.itlong.cloud.POJO.VO.sdk.DeveloperAuthSafeSettingsVO;
import com.itlong.cloud.POJO.VO.sdk.SDKServerAppUserSaveVO;
import com.itlong.cloud.POJO.VO.sdk.SDKServerUserCacheVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.constants.RedisConstant;
import com.itlong.cloud.enumerate.*;
import com.itlong.cloud.operate.dao.IOperateDeveloperAuthDao;
import com.itlong.cloud.property.service.IPropertyHouseHoldInfoService;
import com.itlong.cloud.sdk.dao.ISDKServerOldAppUserDao;
import com.itlong.cloud.sdk.dao.ISDKServerOldPropertyUserDao;
import com.itlong.cloud.sdk.service.ISDKServerOldUserService;
import com.itlong.cloud.service.RedisService;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.utils.data.handler.SqlUtil;
import com.itlong.cloud.utils.encrypt.Md5EncryptUtil;
import com.itlong.cloud.utils.encrypt.UserTokenUtil;
import com.itlong.cloud.utils.page.Page;
import com.itlong.cloud.utils.random.LogicIdUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <desc>
 * SDK人员服务层实现类
 * </desc>
 *
 * @createDate 2017/10/27
 */
@Service
public class SDKServerOldUserServiceImpl implements ISDKServerOldUserService {

    @Autowired
    ISDKServerOldPropertyUserDao isdkUserDao;

    //Redis工具接口类
    @Autowired
    private RedisService<SDKServerUserCacheVO> redisService;

    @Autowired
    ISDKServerOldAppUserDao iSDKServerOldAppUserDao;

    @Autowired
    IPropertyHouseHoldInfoService iPropertyHouseHoldInfoService;
    @Autowired
    private IOperateDeveloperAuthDao iOperateDeveloperAuthDao;

    /**
     * <desc>
     * SDK校验登录用户
     * <desc/>
     *
     * @param appid 独立开发者userId
     * @param token 登录令牌
     * @return SDKServerUserCacheVO   校验人员返回VO
     * @author Biao.R
     * @createDate 2017/10/27
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public SDKServerUserCacheVO checkSDKCacheUser(String appid, String token) {
        if (StringUtils.isNotEmpty(appid) && StringUtils.isNotEmpty(token)) {
            String cacheKey = String.format("%s%s", RedisConstant.SDKSERVER_USER_REDIS_KEY, appid);
            SDKServerUserCacheVO cacheUser = redisService.getObject(cacheKey, SDKServerUserCacheVO.class);
            if (cacheUser != null && token.equals(cacheUser.getToken())) {
                cacheUser.setLastOperateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                redisService.set(cacheKey, RedisConstant.SDKSERVER_LOGIN_TIME, cacheUser);
                return cacheUser;
            }
        }
        return null;
    }

    /**
     * <desc>
     * SDK申请项目时，绑定appid为当前项目的独立开发者
     * <desc/>
     *
     * @param roleProjectPO 物业角色与人员之间的关系
     * @return Integer   添加的数量
     * @author Biao.R
     * @createDate 2017/11/1
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public Integer saveRoleProject(PropertyRoleProjectPO roleProjectPO) {
        try {
            if (roleProjectPO != null) {
                Map<String, Object> params = new HashMap<>();
                params.put("projectId", roleProjectPO.getProjectId());
                params.put("userId", roleProjectPO.getUserId());
                List<PropertyRoleProjectPO> result = isdkUserDao.getRoleProjectByParams(params);
                if (result == null || result.isEmpty()) {
                    //数据库中没有时才添加
                    roleProjectPO.setCreateTime(new Date());
                    roleProjectPO.setStatus(DataStatusEnum.NORMAL.getType());
                    return isdkUserDao.save(SqlUtil.durableData(roleProjectPO, PlatformConstants.TABLE_SAVE));
                }
            }
        } catch (Exception e) {
            throw new DataAccessException("saveRoleProject异常", e);
        }
        return null;
    }

    /**
     * <desc>
     * 查询PropertyRoleProjectPO
     * <desc/>
     *
     * @param roleProjectPO 查询条件对象
     * @return List<PropertyRoleProjectPO>  查询的对象结果集
     * @author Biao.R
     * @createDate 2017/11/3
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public List<PropertyRoleProjectPO> getRoleProject(PropertyRoleProjectPO roleProjectPO) {
        if (roleProjectPO != null) {
            Map<String, Object> params = new HashMap<>();
            params.put("projectId", roleProjectPO.getProjectId());
            params.put("userId", roleProjectPO.getUserId());
            params.put("roleId", roleProjectPO.getRoleId());
            List<PropertyRoleProjectPO> roleProjectPOs = isdkUserDao.getRoleProjectByParams(params);
            return roleProjectPOs;
        }
        return null;
    }

    /**
     * <desc>
     * SDK服务端登录
     * <desc/>
     *
     * @param appid     应用接入凭证
     * @param appsecret 应用接入密钥
     * @return 缓存对象
     * @author Biao.R
     * @createDate 2017/11/9
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public SDKServerUserCacheVO sdkServerLogin(String appid, String appsecret) {
        try {
            if (StringUtils.isNotEmpty(appid) && StringUtils.isNotEmpty(appsecret)) {
                //数据库校验appid和appsecret
                Map<String, Object> params = new HashMap<>();
                params.put("userId", appid);
                params.put("appsecret", appsecret);
                params.put("status", DataStatusEnum.NORMAL.getType());
                List<PropertyUserInfoPO> userPOs = isdkUserDao.getUserByParams(params);
                if (userPOs != null && !userPOs.isEmpty()) {
                    //更新redis缓存，清空旧的缓存,server端缓存时间无时间限制
                    String redisKey = String.format("%s%s", RedisConstant.SDKSERVER_USER_REDIS_KEY, appid);
                    String userName = userPOs.get(0).getUserName();
                    String token = UserTokenUtil.tokenEncrypt(appid, PlatformConstants.SDKSERVER_USER_TOKEN_KEY, SystemTypeEnum.SDK_SERVER.getType());
                    String loginDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
                    SDKServerUserCacheVO serverCacheUser = new SDKServerUserCacheVO(appid, userName, appsecret, token, loginDate);
                    serverCacheUser.setLastOperateTime(loginDate);
                    redisService.set(redisKey, RedisConstant.SDKSERVER_LOGIN_TIME, serverCacheUser);
                    return serverCacheUser;
                }
            }
            return null;
        } catch (UnsupportedEncodingException e) {
            throw new DataAccessException("【SDK服务端登录_SDKServerUserServiceImpl_sdkServerLogin】处理异常", e);
        }
    }

    /**
     * <desc>
     * 添加业主或者家人
     * <desc/>
     *
     * @param sdkSaveAppUserDTO 被授权的对象
     * @return 返回的用户及其房间信息
     * @author Biao.R
     * @createDate 2017/11/16
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public SDKServerAppUserSaveVO addHouserOrFamily(SDKSaveAppUserDTO sdkSaveAppUserDTO) {
        try {
            String authUserId = sdkSaveAppUserDTO.getAuthUserId();
            String projectId = sdkSaveAppUserDTO.getProjectId();
            Integer houseType = sdkSaveAppUserDTO.getHouseType();
            String userRemarks = sdkSaveAppUserDTO.getUserRemarks();
            Set<String> userIdSet = new HashSet<>();
            List<Map<String, Object>> roomList = new ArrayList<>();
            SDKServerAppUserSaveVO saveVO = new SDKServerAppUserSaveVO(sdkSaveAppUserDTO.getUserPhone());
            List<SDKRoomInfoSaveDTO> userRoomList = sdkSaveAppUserDTO.getUserRoomList();

            Date currentTime = new Date();

            List<Map<String, Object>> saveUserRoomList = new ArrayList<>();
            List<AppUserRoomPO> updateUserRoomList = new ArrayList<>();
            //List<Map<String, Object>> updateAuthRelationList = new ArrayList<>();

            //处理用户表和用户项目表
            String userId = this.userProjectHandler(sdkSaveAppUserDTO);

            //根据房间来处理用户房间表
            if (userRoomList != null && !userRoomList.isEmpty()) {
                for (SDKRoomInfoSaveDTO userRoomDTO : userRoomList) {
                    String roomId = userRoomDTO.getRoomId();
                    AppUserInfoPO oldHouser = null;

                    //如果是邀请家人，默认家人的房间来源是邀请
                    Integer roomSource = AppUserRoomSourceEnum.USERROOM_SOURCE_INVITE.getType();

                    //业主的部分数据需要单独处理
                    if (AppUserRoomHouserTypeEnum.USERROOM_HOUSERTYPE_OWNER.getType() == houseType) {
                        //由于授权业主是全量更新，该用户原有的业主房间需要标记删除
                        Map<String, Object> getOldRoomParam = new HashMap<>();
                        getOldRoomParam.put("projectId", projectId);
                        getOldRoomParam.put("userId", userId);
                        getOldRoomParam.put("houserType", houseType);
                        List<AppUserRoomPO> oldUserRooms = iSDKServerOldAppUserDao.getUserRoomByParam(getOldRoomParam);
                        if (oldUserRooms != null && !oldUserRooms.isEmpty()) {
                            for (AppUserRoomPO oldUserRoom : oldUserRooms) {
                                oldUserRoom.setStatus(DataStatusEnum.DELETE.getType());
                                oldUserRoom.setUpdateTime(currentTime);
                                updateUserRoomList.add(oldUserRoom);
                            }
                        }

                        //如果原来的房间中已经存在了不是自己的业主，需要将原业主变为新业主授权的家人
                        Map<String, Object> getOldHouserParam = new HashMap<>();
                        getOldHouserParam.put("projectId", projectId);
                        getOldHouserParam.put("roomId", roomId);
                        getOldHouserParam.put("notUserId", userId);
                        getOldHouserParam.put("houserType", houseType);
                        List<AppUserRoomPO> oldHouserOwners = iSDKServerOldAppUserDao.getUserRoomByParam(getOldHouserParam);
                        if (oldHouserOwners != null && !oldHouserOwners.isEmpty()) {
                            for (AppUserRoomPO oldHouserOwner : oldHouserOwners) {
                                String oldHouserUserId = oldHouserOwner.getUserId();
                                oldHouser = iSDKServerOldAppUserDao.getUserByUserId(oldHouserUserId);
                                userIdSet.add(oldHouserUserId);
                                oldHouserOwner.setUpdateTime(currentTime);
                                oldHouserOwner.setHouserType(AppUserRoomHouserTypeEnum.USERROOM_HOUSERTYPE_RELATIVES.getType());
                                oldHouserOwner.setStatus(DataStatusEnum.NORMAL.getType());
                                updateUserRoomList.add(oldHouserOwner);
                            }
                        }
                        roomSource = AppUserRoomSourceEnum.USERROOM_SOURCE_ADD.getType();
                    }

                    //检查该用户是否已经在该房间内存在
                    Map<String, Object> param = new HashMap<>();
                    param.put("roomId", roomId);
                    param.put("userId", userId);
                    List<AppUserRoomPO> oldUserRooms = iSDKServerOldAppUserDao.getUserRoomByParam(param);
                    AppUserRoomPO appUserRoomPO;
                    if (oldUserRooms != null && !oldUserRooms.isEmpty()) {
                        //用户房间已存在
                        appUserRoomPO = oldUserRooms.get(0);
                        appUserRoomPO.setUserRoomStatus(AppUserRoomStatusEnum.USERROOM_STATUS_MOVEIN.getType());
                        appUserRoomPO.setHouserType(houseType);
                        appUserRoomPO.setStatus(DataStatusEnum.NORMAL.getType());
                        appUserRoomPO.setSource(roomSource);
                        appUserRoomPO.setUpdateTime(currentTime);
                        updateUserRoomList.add(appUserRoomPO);
                    } else {
                        //用户房间关系不存在，添加
                        appUserRoomPO = new AppUserRoomPO(userId, projectId, userRoomDTO.getBuildId(),
                                userRoomDTO.getUnitId(), userRoomDTO.getRoomNum(), roomId,
                                AppUserRoomStatusEnum.USERROOM_STATUS_MOVEIN.getType(), houseType, roomSource,
                                DataStatusEnum.NORMAL.getType(), currentTime);
                        appUserRoomPO.setUpdateTime(currentTime);
                        saveUserRoomList.add(SqlUtil.durableData(appUserRoomPO, PlatformConstants.TABLE_SAVE));
                    }

                    if (AppUserRoomHouserTypeEnum.USERROOM_HOUSERTYPE_OWNER.getType() == houseType) {
                        //处理授权关系表：新业主为独立开发者授权，原房间的旧业主由新业主授权重新授权为家属
                        Map<String, Object> paramMap = new HashMap<>();
                        paramMap.put("projectId", projectId);
                        paramMap.put("roomId", roomId);
                        List<AppAuthRelationsPO> authRelationsPOS = iSDKServerOldAppUserDao.getAuthRelationsByParams(paramMap);
                        if (authRelationsPOS != null && !authRelationsPOS.isEmpty()) {
                            for (AppAuthRelationsPO authRelationsPO : authRelationsPOS) {
                                if (!userId.equals(authRelationsPO.getParentUserId())) {
                                    authRelationsPO.setParentUserId(userId);
                                    authRelationsPO.setUpdateTime(currentTime);
                                    iSDKServerOldAppUserDao.updateAuthRelations(authRelationsPO);
                                }
                            }
                        }
                    } else {
                        //家属保存授权权限
                        Map<String, Object> paramMap = new HashMap<>();
                        paramMap.put("projectId", projectId);
                        paramMap.put("roomId", roomId);
                        paramMap.put("userId", userId);
                        List<AppAuthRelationsPO> authRelationsPOS = iSDKServerOldAppUserDao.getAuthRelationsByParams(paramMap);
                        if (authRelationsPOS == null || authRelationsPOS.isEmpty()) {
                            AppAuthRelationsPO authRelationsPO = new AppAuthRelationsPO(userId, authUserId, projectId,
                                    userRoomDTO.getBuildId(), userRoomDTO.getUnitId(), userRoomDTO.getRoomId(), userRoomDTO.getRoomNum(), DataStatusEnum.NORMAL.getType(), currentTime);
                            authRelationsPO.setUserRemarks(userRemarks);
                            iSDKServerOldAppUserDao.save(SqlUtil.durableData(authRelationsPO, PlatformConstants.TABLE_SAVE));
                        }
                    }
                    Map<String, Object> roomMap = new HashMap<>();
                    roomMap.put("roomId", roomId);
                    if (oldHouser != null) {
                        roomMap.put("originalHouser", oldHouser.getPhoneNum());
                    }
                    roomList.add(roomMap);
                }
            }

            //持久化数据
            if (updateUserRoomList != null && !updateUserRoomList.isEmpty()) {
                iSDKServerOldAppUserDao.batchUpdateUserRoom(updateUserRoomList);
            }
            if (saveUserRoomList != null && !saveUserRoomList.isEmpty()) {
                iSDKServerOldAppUserDao.batchSaveUserRoom(saveUserRoomList);
            }

            //权限处理
            userIdSet.add(userId);
            iPropertyHouseHoldInfoService.updateAppUserAuth(new ArrayList<>(userIdSet), authUserId, projectId);
            saveVO.setRoomList(roomList);
            return saveVO;
        } catch (Exception e) {
            throw new DataAccessException("【SDK服务端_SDKServerOldUserServiceImpl_addHouser】授权业主或家属异常", e);
        }
    }


    /**
     * <desc>
     * 批量添加App用户：包括用户项目，用户房间，及权限处理
     * <desc/>
     *
     * @param saveAppUserDTOs 待添加的用户及房间信息
     * @return 返回添加的数量Map
     * @author Biao.R
     * @createDate 2017/11/23
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public Map<String, Object> addAppUsers(List<SDKSaveAppUserDTO> saveAppUserDTOs) {
        try {
            if (saveAppUserDTOs == null || saveAppUserDTOs.isEmpty()) {
                return null;
            }
            Date currentTime = new Date();
            Set<String> userIdSet = new HashSet<>();
            int existUserCount = 0;
            for (SDKSaveAppUserDTO saveAppUserDTO : saveAppUserDTOs) {
                List<AppUserRoomPO> updateUserRoomList = new ArrayList<>();
                List<Map<String, Object>> saveUserRoomList = new ArrayList<>();
                String projectId = saveAppUserDTO.getProjectId();
                String authUserId = saveAppUserDTO.getAuthUserId();
                List<SDKRoomInfoSaveDTO> userRoomList = saveAppUserDTO.getUserRoomList();

                //处理用户表和用户项目表
                String userId = this.userProjectHandler(saveAppUserDTO);

                //处理用户房间表
                if (userRoomList != null && !userRoomList.isEmpty()) {
                    for (SDKRoomInfoSaveDTO userRoomDTO : userRoomList) {
                        String roomId = userRoomDTO.getRoomId();

                        //查询该用户是否在该房间内存在：不存在才进行操作
                        Map<String, Object> getUserRoomParam = new HashMap<>();
                        getUserRoomParam.put("projectId", projectId);
                        getUserRoomParam.put("roomId", roomId);
                        getUserRoomParam.put("userId", userId);
                        List<AppUserRoomPO> userRoomPOS = iSDKServerOldAppUserDao.getUserRoomByParam(getUserRoomParam);
                        if (userRoomPOS == null || userRoomPOS.isEmpty()) {

                            //查询该房间内的业主是否存在: 不存在则默认为该房间的业主
                            Integer houseType = AppUserRoomHouserTypeEnum.USERROOM_HOUSERTYPE_OWNER.getType();
                            Map<String, Object> getOldHouserParam = new HashMap<>();
                            getOldHouserParam.put("projectId", projectId);
                            getOldHouserParam.put("roomId", roomId);
                            getOldHouserParam.put("houserType", AppUserRoomHouserTypeEnum.USERROOM_HOUSERTYPE_OWNER.getType());
                            List<AppUserRoomPO> oldHouserOwners = iSDKServerOldAppUserDao.getUserRoomByParam(getOldHouserParam);
                            if (oldHouserOwners != null && !oldHouserOwners.isEmpty()) {
                                //如果业主存在，并且不是自己，则添加为该房间的家属
                                houseType = AppUserRoomHouserTypeEnum.USERROOM_HOUSERTYPE_RELATIVES.getType();
                            }

                            AppUserRoomPO appUserRoomPO = new AppUserRoomPO(userId, projectId, userRoomDTO.getBuildId(),
                                    userRoomDTO.getUnitId(), userRoomDTO.getRoomNum(), roomId,
                                    AppUserRoomStatusEnum.USERROOM_STATUS_MOVEIN.getType(), houseType,
                                    AppUserRoomSourceEnum.USERROOM_SOURCE_ADD.getType(), DataStatusEnum.NORMAL.getType(), currentTime);
                            appUserRoomPO.setUpdateTime(currentTime);
                            saveUserRoomList.add(SqlUtil.durableData(appUserRoomPO, PlatformConstants.TABLE_SAVE));
                            userIdSet.add(userId);
                        } else {
                            //如果该用户在该房间已经存在，更新时间和状态
                            AppUserRoomPO appUserRoomPO = userRoomPOS.get(0);
                            appUserRoomPO.setStatus(DataStatusEnum.NORMAL.getType());
                            appUserRoomPO.setUpdateTime(currentTime);
                            updateUserRoomList.add(appUserRoomPO);
                            existUserCount++;
                        }

                    }
                }

                //持久化数据
                if (updateUserRoomList != null && !updateUserRoomList.isEmpty()) {
                    iSDKServerOldAppUserDao.batchUpdateUserRoom(updateUserRoomList);
                }
                if (saveUserRoomList != null && !saveUserRoomList.isEmpty()) {
                    iSDKServerOldAppUserDao.batchSaveUserRoom(saveUserRoomList);
                }

                iPropertyHouseHoldInfoService.updateAppUserAuth(new ArrayList<>(userIdSet), authUserId, projectId);

            }
            Map<String, Object> countMap = new HashMap<>();
            countMap.put("existUser", existUserCount);
            countMap.put("addUserCount", userIdSet.size());
            return countMap;
        } catch (Exception e) {
            throw new DataAccessException("【SDK服务端_SDKServerOldUserServiceImpl_addAppUsers】添加App用户异常", e);
        }
    }


    /**
     * <desc>
     * 根据参数查询用户房间关联表
     * <desc/>
     *
     * @param params 查询参数
     * @return List<AppUserRoomPO>    查询出的用户房间结果集
     * @author Biao.R
     * @createDate 2017/11/21
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public List<AppUserRoomPO> getUserRoomByParam(Map<String, Object> params) {
        return iSDKServerOldAppUserDao.getUserRoomByParam(params);
    }


    /**
     * <desc>
     * 根据参数查询授权关系表
     * <desc/>
     *
     * @param paramMap 查询参数集
     * @return 查询到的授权关系对象集
     * @author Biao.R
     * @createDate 2017/11/21
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public List<AppAuthRelationsPO> getAuthRelationsByParams(Map<String, Object> paramMap) {
        return iSDKServerOldAppUserDao.getAuthRelationsByParams(paramMap);
    }

    /**
     * <desc>
     * 根据手机号查询APP用户
     * <desc/>
     *
     * @param phoneNum 待查询的手机号
     * @return 查询到的用户信息
     * @author Biao.R
     * @createDate 2017/11/22
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public AppUserInfoPO getAppUserByPhone(String phoneNum) {
        return iSDKServerOldAppUserDao.getAppUserByPhone(phoneNum);
    }

    /**
     * <desc>
     * 分页查询被授权人列表
     * <desc/>
     *
     * @param sdkAuthUserGetPageDTO 查询参数对象
     * @return 返回分页对象结果
     * @author Biao.R
     * @createDate 2017/11/22
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public Page<AppAuthRelationsPO> getAuthRelationsPage(SDKAuthUserGetPageDTO sdkAuthUserGetPageDTO) {
        Page<AppAuthRelationsPO> page = new Page<>();
        Map<String, Object> params = new HashMap<>();
        params.put("parentPhone", sdkAuthUserGetPageDTO.getUserPhone());
        Integer pageSize = sdkAuthUserGetPageDTO.getPageSize();
        Integer pageNo = sdkAuthUserGetPageDTO.getPageNo();
        page.getPage().setCurrentPage(pageNo == null ? "1" : pageNo.toString());
        page.getPage().setPageSize(pageSize == null ? "10" : pageSize.toString());
        params.put("currentPage", page.getPage().getStartSlip());
        params.put("pageSize", page.getPage().getPageSize());
        params.put("projectId", sdkAuthUserGetPageDTO.getProjectId());
        page.setRows(iSDKServerOldAppUserDao.getAuthRelationsPageList(params), iSDKServerOldAppUserDao.getAuthRelationsPageCount(params));
        return page;
    }

    /**
     * <desc>
     * 根据userId查询AppUser
     * <desc/>
     *
     * @param userId 待查询的userId
     * @return 查询出的appUser对象
     * @author Biao.R
     * @createDate 2017/11/22
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public AppUserInfoPO getAppUserByUserId(String userId) {
        return iSDKServerOldAppUserDao.getUserByUserId(userId);
    }

    /**
     * <desc>
     * 更新授权关系表
     * <desc/>
     *
     * @param authRelationsPO 待更新对象
     * @return 更新数量
     * @author Biao.R
     * @createDate 2017/11/23
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public Integer updateAuthRelations(AppAuthRelationsPO authRelationsPO) {
        try {
            if (authRelationsPO != null) {
                return iSDKServerOldAppUserDao.updateAuthRelations(authRelationsPO);
            }
            return null;
        } catch (Exception e) {
            throw new DataAccessException("【SDK服务端_SDKServerOldUserServiceImpl_updateAuthRelations】更新授权关系表异常", e);
        }
    }


    /**
     * <desc>
     * 添加App用户时，对app_user_info,app_user_project表的影响
     * <desc/>
     *
     * @param sdkSaveAppUserDTO 添加用户数据DTO
     * @return 添加后的userId
     * @author Biao.R
     * @createDate 2017/11/23
     */
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public String userProjectHandler(SDKSaveAppUserDTO sdkSaveAppUserDTO) throws Exception {
        String phoneNum = sdkSaveAppUserDTO.getUserPhone();
        String projectId = sdkSaveAppUserDTO.getProjectId();

        //通过手机号查询被授权人是否在数据库中已经存在
        Date currentTime = new Date();
        String userId = "";
        AppUserInfoPO appUser = iSDKServerOldAppUserDao.getAppUserByPhone(phoneNum);
        if (appUser == null) {
            //查询手机的用户不存在,添加
            userId = LogicIdUtil.userBusinessId();
            String realName = String.format("%s%s%s", phoneNum.substring(0, 3), "****", phoneNum.substring(7));
            appUser = new AppUserInfoPO(userId, realName, realName, Md5EncryptUtil.md5(phoneNum), phoneNum, AppUserGenderEnum.USERINFO_GENDER_MAN.getType(), null);
            appUser.setStatus(DataStatusEnum.NORMAL.getType());
            appUser.setCreateTime(currentTime);
            iSDKServerOldAppUserDao.save(SqlUtil.durableData(appUser, PlatformConstants.TABLE_SAVE));
        } else {
            userId = appUser.getUserId();
            appUser.setStatus(DataStatusEnum.NORMAL.getType());
            appUser.setUpdateTime(currentTime);
            iSDKServerOldAppUserDao.update(SqlUtil.durableData(appUser, PlatformConstants.TABLE_UPDATE));
        }

        // 处理用户项目表
        Map<String, Object> params = new HashMap<>();
        params.put("projectId", projectId);
        params.put("userId", userId);
        List<AppUserProjectPO> userProjectPOs = iSDKServerOldAppUserDao.getUserProject(params);
        AppUserProjectPO userProjectPO = null;
        if (userProjectPOs == null || userProjectPOs.isEmpty()) {
            userProjectPO = new AppUserProjectPO(userId, projectId, AppUserProjectTypeEnum.USERPROJECT_TYPE_SELF.getType().toString(),
                    "000000", AppUserProjectStatusEnum.USERPROJECT_USERPROJECTSTATUS_ENABLE.getType().toString(),
                    AppUserProjectUserTypeEnum.USERPROJECT_USERTYPE_ORDINARY.getType(), DataStatusEnum.NORMAL.getType(), currentTime);
            iSDKServerOldAppUserDao.save(SqlUtil.durableData(userProjectPO, PlatformConstants.TABLE_SAVE));
        } else {
            userProjectPO = userProjectPOs.get(0);
            userProjectPO.setUpdateTime(currentTime);
            userProjectPO.setStatus(DataStatusEnum.NORMAL.getType());
            iSDKServerOldAppUserDao.updateUserProject(userProjectPO);
        }
        return userId;
    }

    /**
     * <desc>
     * 获取物业用户信息，条件：userId
     * </desc>
     *
     * @param appid 即userId
     * @return 物业用户信息
     * @author wangzhi
     * @createDate 2018/12/19
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public PropertyUserInfoPO getPropertyUserByAppId(String appid) throws Exception {
        return isdkUserDao.getPropertyUserByAppId(appid);
    }

    /**
     * <desc>
     * 获取开发者授权安全设置信息，条件：userId
     * </desc>
     *
     * @param appid 即userId
     * @return 开发者授权安全设置VO
     * @author wangzhi
     * @createDate 2018/12/19
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public DeveloperAuthSafeSettingsVO getSafeSettings(String appid) throws Exception {
        return isdkUserDao.getSafeSettings(appid);
    }

    /**
     * <desc>
     * 获取物业用户信息，条件：userName
     * </desc>
     *
     * @param appid 即userName
     * @return 物业用户信息
     * @author wangzhi
     * @createDate 2018/12/19
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public PropertyUserInfoPO getPropertyUserByUserName(String appid) throws Exception {
        return isdkUserDao.getPropertyUserByUserName(appid);
    }

    /**
     * <desc>
     * 获取机器人编号
     * </desc>
     *
     * @param appid 即userName
     * @return 机器人编号
     * @author maju
     * @createDate 2021/05/26
     */
    @Override
    public String getRobotDevelopRobotInfo(String appid) {
        Map<String, Object> params = new HashMap<>();
        params.put("userId", appid);
        return iOperateDeveloperAuthDao.getRobotDevelopRobotInfo(params);
    }
}